import React, { useEffect, useState, useCallback } from "react";
import { Form, Input, Select, Button, message, Radio, DatePicker, TimePicker } from 'antd';
import moment from 'moment'
import { savePlan, updatePlan, queryTriggerType, queryProductType, queryCallType, listCustomerEvent } from "../../utils/service";
import { DEFAULT_CONFIG } from '../../utils/const';
import CirclePeople from '../circlePeople'
import CycleTime from '../cycleTime'
import SearchSelect from "../searchSelect";
import './index.scss';
import locale from 'antd/es/date-picker/locale/zh_CN';

const { Option } = Select;

const DrawerForm = Form.create({
  name: 'addOrUpdateForm',
})(props => {
  const { form, backfillValues = {}, handelCloseDrawer, visible, setLoading } = props;
  /** 表单是否编辑 */
  const isEdit = !!backfillValues?.id;
  const { getFieldDecorator, validateFieldsAndScroll, getFieldValue } = form;
  // const dataType = getFieldValue('dataType') 
  const [triggerTypeList, setTriggerTypeList] = useState([])
  const [productTypeList, setProductTypeList] = useState([])
  const [callTypeList, setCallTypeList] = useState([])

  useEffect(() => {
    queryTriggerType({}).then(res => {
      if (res.success) {
        const { data = [] } = res
        getValueCode(data, setTriggerTypeList)
      }
    }).catch(err => { })
    queryProductType({}).then(res => {
      if (res.success) {
        const { data = [] } = res
        getValueCode(data, setProductTypeList)
      }
    }).catch(err => { })
    queryCallType({}).then(res => {
      if (res.success) {
        const { data = [] } = res
        getValueCode(data, setCallTypeList)
      }
    }).catch(err => { })

  }, [])

  const getValueCode = (data = [], setData) => {
    const arr = []
    data.forEach(item => {
      arr.push({
        label: item.name,
        value: item.code
      })
    })
    setData(arr)
  }

  /** 表单提交 */
  const handleSubmit = (e) => {
    e.preventDefault();
    validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        try {
          setLoading?.(true);
          const { cycleConfig = {}, scheduleTime, dataType, groupId, ids, scheduleType, sql, cronExpression, triggerType } = values
          const timeFormat = scheduleType == 'fixed_time' ? 'YYYY-MM-DD HH:mm:ss' : 'HH:mm:ss'
          const { textContent } = sql || {}
          const params = {
            ...values,
            dataSource: JSON.stringify({
              dataType,
              groupId,
              ids,
              sql: textContent
            }),
            triggerConfig: JSON.stringify({
              scheduleType,
              scheduleTime: scheduleTime ? scheduleTime.format(timeFormat) : '',
              cronExpression,
              ...cycleConfig,
            }),
          }
          delete params.cycleConfig
          delete params.dataType
          delete params.groupId
          delete params.ids
          delete params.sql
          delete params.scheduleTime
          delete params.scheduleType
          delete params.triggerOppType
          delete params.cronExpression
          triggerType !== 'schedule' && delete params.triggerConfig
          triggerType === 'old_default' && delete params.dataSource
          // console.log(params, 'params')
          // return
          const { success, message: msg } = await (isEdit ? updatePlan(params) : savePlan(params));
          if (success) {
            message.success(isEdit ? '修改成功' : '新增成功');
            handelCloseDrawer?.();
          } else {
            message.error('操作失败:' + msg);
          }
          setLoading?.(false);
        } catch (error) {
          setLoading?.(false);
          message.error('操作失败:' + error);
          console.error(error);
        }
      }
    });
  }

  /** 渲染表单项 */
  const renderItem = (item, value, dataType) => {
    const { placeholder = '', searchService, name, allowClear } = item
    switch (item?.uiType) {
      case 'textArea':
        return <Input.TextArea placeholder={placeholder || "请输入" + name} disabled={item?.editAble === false} allowClear={allowClear} autoSize={{
          minRows: 4,
          maxRows: 10
        }} />
      case 'select':
        return (
          <Select placeholder={placeholder || "请选择" + name} disabled={item?.editAble === false} allowClear={allowClear}>
            {
              (item?.enum || [])?.map(option => (
                <Option key={option?.value} value={option?.value}>{option?.label}</Option>
              ))
            }
          </Select>
        );
      case 'radio':
        return (
          <Radio.Group >
            {
              (item?.enum || [])?.map(option => (
                <Radio value={option?.value}>{option?.label}</Radio>
              ))
            }
          </Radio.Group>
        )
      case 'circlePeople':
        return <CirclePeople {...item} />
      case 'datePicker':
        return <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime locale={{
          ...locale,
          lang: {
            ...locale.lang,
            shortWeekDays: ['日', '一', '二', '三', '四', '五', '六'],
            shortMonths: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"
            ]
          }
        }} placeholder={placeholder || "请选择" + name} />
      case 'cycleTime':
        return <CycleTime {...item} placeholder={placeholder || "请选择" + name} defaultValue={value} />
      case 'timePicker':
        return <TimePicker format="HH:mm:ss" placeholder={placeholder || "请选择" + name} />
      case 'searchSelect':
        return <SearchSelect disabled={item?.editAble === false} dataType={dataType} placeholder={placeholder || "清输入并选择" + name} searchService={searchService} />
      default:
        return <Input placeholder={placeholder || "请输入" + name} disabled={item?.editAble === false} />
    }
  }


  function handleFormItem(item, getFieldValue, renderFormItem) {
    if (!item || !typeof getFieldValue == "function" || !typeof renderFormItem == "function") {
      return null
    }
    const { relyFn, requiredFn, setEnum } = item || {}
    const dataType = getFieldValue('dataType')
    console.log(dataType,3333);
    const triggerType = getFieldValue('triggerType')
    if (typeof requiredFn == 'function') {
      const required = requiredFn(getFieldValue)
      item.required = required
    }
    if (typeof setEnum == 'function') {
      item.enum = setEnum(getFieldValue)
    }
    if (typeof relyFn == 'function') {
      const isShow = relyFn(getFieldValue)
      return isShow && renderFormItem(item, dataType) || null
    }
    return renderFormItem(item, dataType)
  }


  const setRenderFields = () => {
    return DEFAULT_CONFIG.map(item => {
      if (item.key === 'bizScene') {
        item.enum = callTypeList
      }
      if (item.key === 'productType') {
        item.enum = productTypeList
      }
      if (item.key === 'triggerType') {
        item.enum = triggerTypeList
      }
      return item
    })
  }

  const renderForm = useCallback(
    (data) => {
      return (
        Array.isArray(data) &&
        data.map((item, index) => {
          return handleFormItem(item, getFieldValue, renderFormItem);
        })
      );
    },
    []
  );

  /** 渲染form字段 */
  const renderFormItem = (item, dataType) => {
    let backfillValuesData = { ...backfillValues }
    if (backfillValues.id) {
      const triggerConfig = backfillValues?.triggerConfig ? JSON.parse(backfillValues.triggerConfig) : {}
      const dataSource = backfillValues?.dataSource ? JSON.parse(backfillValues.dataSource) : {}
      const { scheduleType } = triggerConfig
      const timeFormat = scheduleType == 'fixed_time' ? 'YYYY-MM-DD HH:mm:ss' : 'HH:mm:ss'
      backfillValuesData = {
        ...backfillValues,
        ...dataSource,
        sql: {
          textContent: dataSource?.sql,   // 客户列表   
          legitimate: true   //圈人是否可提交状态
        },
        cycleConfig: {
          cyclePeriod: triggerConfig.cyclePeriod || '',
          cycleDate: triggerConfig.cycleDate || ''
        },
        ...triggerConfig,
        scheduleTime: triggerConfig.scheduleTime ? moment(triggerConfig.scheduleTime, timeFormat) : '',
      }
      delete backfillValuesData.dataSource;
      delete backfillValuesData.triggerConfig;
    }
    if (item?.editAble === false && !isEdit) return null;
    if (item?.disabled) return null
    return (
      <Form.Item
        label={item?.name}
        extra={item?.tips}
        required={item?.required}
      >
        {
          getFieldDecorator(item?.key, {
            initialValue: backfillValuesData?.[item.key] || item?.defaultValue,
            rules: [{ required: item?.required, ...item.rules ? item.rules : { message: item.message || `请输入${item?.name}` } }],
          })(renderItem(item, backfillValuesData?.[item.key], dataType))
        }
      </Form.Item>
    )
  }

  // console.log(backfillValues,'backfillValues')

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  if (!visible) return null;


  return (
    <div className="drawerForm">
      <Form
        {...formItemLayout}
        className="drawerForm_mainForm"
        onSubmit={handleSubmit}
      >
        {renderForm(setRenderFields())}
        <div className="drawerForm_footer">
          <Button style={{ marginRight: 8 }} onClick={handelCloseDrawer}>
            取消
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            data-trace-click="clk-crm-open-form-list-submit"
            data-logmeta={`isEdit=${isEdit}`}
          >
            提交
          </Button>
        </div>
      </Form>
    </div>
  );
});

export default DrawerForm;
